package org.pidan.basic.multiThread;

import java.util.concurrent.TimeUnit;

/**
 * {@code @description}: 中断线程
 * {@code @author}: huangyuxin
 * {@code @date}: 2023-12-12
 */
public class ZhongDuan {

    public static void main(String[] args) throws InterruptedException {

        Thread thread = new Thread() {
            @Override
            public void run() {
                while (true) {
                    try {
                        TimeUnit.SECONDS.sleep(100);

                    } catch (Exception e) {
                        //以下一句如果不写，程序报出异常后，也不会结束。因为sleep方法由于中断而抛出异常之后，线程的中断标志会被清除（置为false
                        this.interrupt();
                        e.printStackTrace();
                    }
                    if (this.isInterrupted()) {
                        System.out.println("break");
                        break;
                    }


                }
            }
        };

        thread.setName("thread1");
        thread.start();
        TimeUnit.SECONDS.sleep(1);
        thread.interrupt();
    }
}
